package pe.com.rimac.portal.facturacion.util;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;

import pe.com.rimac.portal.common.config.ServiceConfig;
import pe.com.rimac.portal.common.holder.RequestHolder;
import pe.com.rimac.portal.facturacion.constantes.Constantes.Configuracion;

import com.ibm.portal.portlet.service.PortletServiceHome;
import com.ibm.portal.portlet.service.PortletServiceUnavailableException;
import com.ibm.portal.portlet.service.credentialvault.CredentialVaultException;
import com.ibm.portal.portlet.service.credentialvault.CredentialVaultService;
import com.ibm.portal.portlet.service.credentialvault.credentials.UserPasswordPassiveCredential;

/**
 * Clase utilitaria para la comunicaci&oacute;n con el porlet service Credential Vault.
 * 
 * @author Andres Deza Villacorta - Synopsis S.A
 * 
 */
public class CredentialUtil
{
	@Autowired
	private ServiceConfig serviceConfig;
	@Autowired
	private PortletServiceHome credentialVaultServiceHome;
	private static final String USER_PASSWORD_PASSIVE_CREDENTIAL = "UserPasswordPassive";

	/**
	 * Obtiene la referencia al {@link CredentialVaultService}
	 * 
	 * @return
	 */
	private CredentialVaultService getCredentialVaultService()
	{
		try
		{
			return (CredentialVaultService) credentialVaultServiceHome.getPortletService(CredentialVaultService.class);
		}
		catch (PortletServiceUnavailableException e)
		{
			throw new RuntimeException("Could not get CredentialVaultService from Home", e);
		}
	}

	/**
	 * Obtiene las credenciales solicitadas.
	 * 
	 * @return
	 */
	private UserPasswordPassiveCredential getPrincipalAndCredential()
	{
		try
		{
			UserPasswordPassiveCredential credential = (UserPasswordPassiveCredential) getCredentialVaultService()
					.getCredential(serviceConfig.getProperty(Configuracion.CREDENTIAL_SLOT_NAME),
							USER_PASSWORD_PASSIVE_CREDENTIAL, new HashMap(), RequestHolder.getPortletRequest());
			return credential;
		}
		catch (CredentialVaultException e)
		{
			throw new RuntimeException(e);
		}
	}

	/**
	 * Obtiene el password de la credencial obtenida.
	 * 
	 * @param request
	 * @return
	 */
	public String getCredentials()
	{
		return String.valueOf(getPrincipalAndCredential().getPassword());
	}

	/**
	 * Obtiene el username de la credencial obtenida.
	 * 
	 * @param request
	 * @return
	 */
	public String getPrincipal()
	{
		return getPrincipalAndCredential().getUserId();
	}
}